// UART1.c
#include "FreeRTOS.h"
#include "HC05.h"
#include "USART.h"
#include "queue.h"
#include "semphr.h"
#include "Flash.h"
#include "OLED.h"
#include <string.h>
extern int GetFromQueue(QueueHandle_t queue, char buf[]/*,char flag[],size_t flagSize8*/);
QueueHandle_t queueHC05;                   // 用来接受HC0C发送消息的消息队列
extern const int address;//密码存储的位置
extern SemaphoreHandle_t   xBinarySemaphoreHC01toESP01;// 等待wifi账号密码获取读取信号量的初始化
extern char wifiname[32];
extern char wifipassword[64];
/*
	引脚配置宏
	当前ESP_TX针脚接入PA10引脚
	当前ESP_RX针脚接入PA9引脚
*/
#define ESP_TX_GPIO_PORT           GPIOA
#define ESP_TX_GPIO_PIN            GPIO_Pin_10
#define ESP_RX_GPIO_PORT           GPIOA
#define ESP_RX_GPIO_PIN            GPIO_Pin_9
#define RCC_APBXPeriph_GPIOX       RCC_APB2Periph_GPIOA
#define RCC_APBXPeriph_USARTX      RCC_APB1Periph_USART3

void HC05_Init(void) {
    // ����ʱ��
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, ENABLE);
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);

    // ��ʼ������
    GPIO_InitTypeDef GPIO_InitStructure;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;//PA2:HC05_TX
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOA, &GPIO_InitStructure);
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;//PA3:HC05_RX
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOA, &GPIO_InitStructure);

    // USART����
    USART_InitTypeDef USART_InitStructure;
    USART_InitStructure.USART_BaudRate = 9600;
    USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
    USART_InitStructure.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;
    USART_InitStructure.USART_Parity = USART_Parity_No;
    USART_InitStructure.USART_StopBits = USART_StopBits_1;
    USART_InitStructure.USART_WordLength = USART_WordLength_8b;
    USART_Init(USART3, &USART_InitStructure);

    USART_ITConfig(USART3, USART_IT_RXNE, ENABLE);
    // NVIC ���ó�ʼ��

    NVIC_InitTypeDef NVIC_InitStructure;
    // ���� NVIC������ HC05���ж�
    NVIC_InitStructure.NVIC_IRQChannel = USART3_IRQn; // ����HC05���ж�
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 12;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);
    // ����HC05
    USART_Cmd(USART3, ENABLE);

    queueHC05 = xQueueCreate(100, 1);//用于接收HC05串口消息的消息队列
}

//
void HC05_SendByte(uint8_t Byte) {
    USART_SendData(USART3, Byte);

    while (USART_GetFlagStatus(USART3, USART_FLAG_TXE) == RESET);
}

void SendToHC05(char *format, ...) { //给HC05打印消息
    char strs[100];
    va_list list;
    va_start(list, format);
    vsprintf(strs, format, list);
    va_end(list);

    for (uint8_t i = 0; strs[i] != '\0'; i++) {
        HC05_SendByte(strs[i]);
        //		USART_SendData(USART2, strs[i]);//打印到串口
    }
}

//将形如!name=passward!的code字符串解析成name和passward，通过wifiname和wifipassword返回
void AnalysisCode(char code[],char wifiname[], char wifipassword[]) {
    int ret = strlen(code);
    if (ret > 0) {
        int i = 0;

        for (int k = 0; code[i + 1] != '='; i++, k++) {
            wifiname[k] = code[i + 1];
        }
        i++;
        for (int k = 0; code[i + 1] != '!'; i++, k++) {
            wifipassword[k] = code[i + 1];
        }
    }
}

//通过蓝牙模块获取密码，并且存入buf
void GetCode(char buffer[]) {
    OLED_Clear();
    OLED_ShowString(1, 1, "plase input wifiname and password");
    if (GetFromQueue(queueHC05, buffer)) {
        xSemaphoreGive(xBinarySemaphoreHC01toESP01);
    }
    int address = 0x0800F000;
    erasePage(address);//擦除页
    changeFlashFor32(address, strlen(buffer));
    for (int i = 0; i < 100; i += 4) {
        changeFlashFor32(address + 4 + i, *(int *)(buffer + i));
    }
    printf2("code write \r\n");
}

int Checkcode(void) {

    int status = 0;
    char buffer[100] = {0};
    status = *((__IO uint32_t *)(address));
    if (status != 0xFFFFFFFF) {   // 有内容
  
        int len = *((__IO uint32_t *)(address));
        readFlash(address + 4, buffer, len);
		AnalysisCode(wifiname,wifipassword, buffer);
        printf2("read: %d, %d, %s \r\n", status, len, buffer);
		xSemaphoreGive(xBinarySemaphoreHC01toESP01);
        return 1;
    } else {
        GetCode(buffer);//从蓝牙获取密码,存入数据
        return 0;
    }
	
}


void USART3_IRQHandler(void) {
    if (USART_GetITStatus(USART3, USART_IT_RXNE) == SET) {
        char data = (uint8_t)USART_ReceiveData(USART3);
        BaseType_t stat = pdTRUE;
        xQueueSendFromISR(queueHC05, &data, &stat);
        USART_ClearITPendingBit(USART3, USART_IT_RXNE);
    }
}
